package com.heima.article.filter;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 获取登录信息的过滤器
 */
@Component
@WebFilter(filterName = "AppTokenFilter",urlPatterns = "/*")
public class AppTokenFilter extends GenericFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        //取出请求头的userId
        String userId = request.getHeader("userId");

        //如果存在，则存入ThreadLocal对象中
        if(StringUtils.isNotEmpty(userId) && !userId.equals("0")){ //访客不需要存入ThreadLocal
            ApUser user = new ApUser();
            user.setId(Integer.valueOf(userId));
            ThreadLocalUtils.set(user);
        }

        //放行
        filterChain.doFilter(request,response);
    }
}
